package com.example.service;

import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Artwork;
import com.example.entity.Contest;
import com.example.entity.Teacher;
import com.example.mapper.ArtworkMapper;
import com.example.mapper.ContestMapper;
import com.example.mapper.TeacherMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 作品信息表业务处理
 **/
@Service
public class ArtworkService {

    @Resource
    private ArtworkMapper artworkMapper;
    @Resource
    private ContestMapper contestMapper;
    @Resource
    private TeacherMapper teacherMapper;
    /**
     * 新增
     */
    public void add(Artwork artwork) {
        Contest contest = contestMapper.selectById(artwork.getContestId());
        Teacher teacher = teacherMapper.selectById(contest.getTeacherId());
        artwork.setTeacherId(teacher.getId());
        artworkMapper.insert(artwork);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        artworkMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            artworkMapper.deleteById(id);
        }
    }

    public void updateById(Artwork artwork) {
        Integer id = artwork.getId();
        Integer contestId = artwork.getContestId();
        Integer score = artwork.getScore();
        // 先把数据更新进去
        artworkMapper.updateScoreById(id, score);
        List<Artwork> list = artworkMapper.selectByContestId(contestId);
        if (RankIsNull(list)) { // 第一个作品
            Artwork artwork1 = new Artwork();
            BeanUtils.copyProperties(artwork, artwork1);
            artwork1.setRank(1);
            artwork1.setPrize("一等奖");
            // 更新数据库中的作品信息
            artworkMapper.updateById(artwork1);
            return;
        } else {
            // 检查 list 是否为 null
            if (list != null) {
                // 过滤掉 list 中的 null 元素
                list = list.stream()
                        .filter(Objects::nonNull)
                        .filter(artwork1 -> artwork1.getScore() != null)
                        .collect(Collectors.toList());
                // 根据 score 从高到低排序，处理 score 为 null 的情况
                list.sort((a1, a2) -> {
                    Integer score1 = a1.getScore();
                    Integer score2 = a2.getScore();
                    if (score1 == null && score2 == null) {
                        return 0;
                    } else if (score1 == null) {
                        return 1;
                    } else if (score2 == null) {
                        return -1;
                    } else {
                        return Integer.compare(score2, score1);
                    }
                });

                // 填充排名和奖项
                for (int i = 0; i < list.size(); i++) {
                    Artwork currentArtwork = list.get(i);
                    int rank = i + 1;
                    currentArtwork.setRank(rank);

                    String prize;
                    if (rank <= 2) {
                        prize = "一等奖";
                    } else if (rank <= 5) {
                        prize = "二等奖";
                    } else if (rank <= 10) {
                        prize = "三等奖";
                    } else {
                        prize = "参与奖";
                    }
                    currentArtwork.setPrize(prize);

                    // 更新数据库中的作品信息
                    artworkMapper.updateById(currentArtwork);
                }
            }
        }


    }

    private boolean RankIsNull(List<Artwork> list) {
        if (list == null) {
            return true;
        }
        for (Artwork artwork : list) {
            if (artwork != null && artwork.getRank() != null && artwork.getRank() != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 根据ID查询
     */
    public Artwork selectById(Integer id) {
        return artworkMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Artwork> selectAll(Artwork artwork) {
        return artworkMapper.selectAll(artwork);
    }

    /**
     * 分页查询
     */
    public PageInfo<Artwork> selectPage(Artwork artwork, Integer pageNum, Integer pageSize) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.STUDENT.name().equals(currentUser.getRole())) {
            artwork.setStudentId(currentUser.getId());
        }
        if (RoleEnum.TEACHER.name().equals(currentUser.getRole())) {
            artwork.setTeacherId(currentUser.getId());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Artwork> list = artworkMapper.selectAll(artwork);
        return PageInfo.of(list);
    }

    public List<Artwork> getByContestId(Integer contestId) {
        List<Artwork> list =artworkMapper.selectByContestId(contestId);
        return list;
    }

    // 根据条件查询作品列表
    public List<Artwork> getArtworkList(Map<String, Object> params) {
        return artworkMapper.getArtworkList(params);
    }

    // 根据条件统计作品总数
    public int getTotalCount(Map<String, Object> params) {
        return artworkMapper.getTotalCount(params);
    }
}